package com.wangzhen.spring.validation;

import com.wangzhen.spring.ioc.dependcy.entity.User;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.validation.*;

import java.util.List;
import java.util.Locale;

public class UserValidatorDemo {

    public static void main(String[] args) {
        // 1、创建要校验的对象
        User user = new User();
        // 2、创建MessageSource的具体实现类ResourceBoundleMessageSource
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasename("message");
        messageSource.setDefaultEncoding("UTF-8");
        // 3、指定Errors接口的具体实现
        Errors errors = new BeanPropertyBindingResult(user, "user");
        // 4、调用Validator的validate方法
        Validator validator = new UserValidator();
        validator.validate(user, errors);
        // 5、获取所有的错误reject+rejectValue = ObjectError+FieldError
        List<ObjectError> allErrors = errors.getAllErrors();
        for (ObjectError error : allErrors) {
            System.out.println(messageSource.getMessage(error.getCode(), error.getArguments(), Locale.getDefault()));
        }
    }

    static class UserValidator implements Validator {
        @Override
        public boolean supports(Class<?> clazz) {
            // 判断要校验的类是不是User.class
            return User.class.isAssignableFrom(clazz);
        }

        @Override
        public void validate(Object target, Errors errors) {
            User user = User.class.cast(target);
            // 指定的field字段名称必须在User对象中存在，否则会抛出Invalid property 'xx' of bean class User
            ValidationUtils.rejectIfEmpty(errors, "name", "user.name.notnull");
        }
    }


}
